
import random




from django_redis import get_redis_connection
from redis.client import StrictRedis
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView


# /sms_cods/136000000/


from celery_tasks.sms.tasks import send_sms_code

from users.models import User


class SMSCodeView(APIView):

    def get(self, request, mobile):
        """"
        获取短信验证码
        """
        strict_redis = get_redis_connection('sms_codes')  # type: StrictRedis
        # print(strict_redis)

        # 4.判断是否是60秒内重复调用
        send_flag = strict_redis.get('sms_flag_%s' % mobile)
        # print(send_flag)
        if send_flag:
            return Response({'message': '60秒频繁请求短信验证码'})

        # 1.生成短信验证码
        # 000333
        sms_code = '%06d' % random.randint(0, 999999)
        print('sms_code: ', sms_code)

        # 2.发送短信验证码
        # 参数1: 手机号码
        # 参数2: [短信号码, 有效时间5分钟]
        # 参数3: 使用id为1云通讯短信模板
        # try:
        #     print(sms_code)
        # print(mobile)
        # ccp = sms.CCP()
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
        send_sms_code.delay(mobile, sms_code)


        # if result == 0:
        #     print("发送成功")
        # else:
        #     print("发送失败")
        # result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # print('发送短信验证码:', result)

        # 3.保存短信验证码, Redis
        # sms_1360000000 123456
        # 参数1: 键
        # 参数2: 有效时间: 5分钟
        # strict_redis.setex('sms_%s' % mobile, 60*5, sms_code)
        # sms_flag_1360000000  true   有效时间1分钟
        # strict_redis.setex('sms_flag_%s' % mobile, 60, True)
        # send_flag = strict_redis.get('sms_flag_' + mobile)
        # print(send_flag)

        '''
        使用管道
        提高对数据库的操作，将对数据库的多次操作整合到管道中，进行一次性处理，
        '''
        pipline = strict_redis.pipeline()
        pipline.setex("sms_%s"% mobile, 60*5, sms_code)
        pipline.setex('sms_flag_%s' % mobile, 1, True)
        result=pipline.execute()#　操作成功，返回ｔｒｕｅ

        print(result)
        return Response({'message': 'ok'})

class MobileView(APIView):
    def get(self,request,mobile):
        user = User.objects.filter(mobile=mobile)
        if user:
            raise serializers.ValidationError('号码已经注册')
        return Response(mobile)















